<template>
    <div
        style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; background-color: #f5f7fa; padding: 10px; border: 1px solid #e4e7ed; border-radius: 4px;">
        <span>新增医院</span>
        <el-button type="primary" @click="set">返回</el-button>
    </div>
    <div style="border: groove; border-width: 2px; height: 100%; width: 800px; margin-top: 20px;">
        <header style="margin-top: 30px;margin-left: 20px;margin-right: 20px;margin-bottom: 50px;">
            <el-form label-width="auto" style="max-width: 600px">
                <el-form-item label="医院名称">
                    <el-input v-model="hospdata.name" placeholder="请输入……" />
                </el-form-item>
                <el-form-item label="列表图">
                    <el-upload class="avatar-uploader" v-model="hospdata.hospitalImg"
                        action="http://localhost:5047/api/carousimg/CarousImg" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="hospdata.hospitalImg" :src="hospdata.hospitalImg" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="是否推荐">
                    <el-radio-group v-model="hospdata.isHospital">
                        <el-radio :value="false">是</el-radio>
                        <el-radio :value="true">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="医院人数">
                    <el-input v-model="hospdata.hospitalCount" placeholder="请输入……" />
                </el-form-item>
                <el-form-item label="科室数">
                    <el-input v-model="hospdata.hospitalCountTow" placeholder="请输入……" />
                </el-form-item>
                <el-form-item label="医院科室">

                </el-form-item>
                <div><el-transfer v-model="hospdata.departments" :data="data" :loading="loading" /></div>
                <el-form-item label="详细地址">
                    <el-input v-model="hospdata.hospitalAddTow" placeholder="请输入……" />
                </el-form-item>
                <el-form-item label="医院电话">
                    <el-input v-model="hospdata.hospitalPhone" placeholder="请输入……" />
                </el-form-item>
                <el-form-item label="医院介绍">
                    <!-- 富文本工具栏 -->
                    <div style="border: 1px solid #ccc; border-radius: 4px;">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" :mode="'default'" />
                        <Editor style="height: 500px;" v-model="valueHtml" :defaultConfig="editorConfig"
                            :mode="'default'" @onCreated="handleCreated" @onChange="handleEditorChange" />
                    </div>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="hospadd">提交</el-button>
                    <el-button>取消</el-button>
                </el-form-item>
            </el-form>
        </header>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import router from '@/router'
import { Read, Write } from '@/Http/Axios'
import { useCounterStore } from '@/stores/counter'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { onBeforeUnmount, shallowRef } from 'vue'


const store = useCounterStore()

// 图片预览
const imageUrl = ref('')

// ✅ 修正：只保存图片 URL 字符串
const handleAvatarSuccess = (response: any) => {
    // 假设后端返回 { url: "http://.../xxx.jpg" }
    if (response && response.url) {
        hospdata.hospitalImg = response.url
    } else {
        // 如果直接返回字符串（如某些 mock 接口）
        hospdata.hospitalImg = response
    }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // 你可以暂时注释掉校验，先确保流程通
    return true
}

// ✅ 修正：departments 应为 number[]（选中的科室ID列表）
const hospdata = reactive({
    name: '',
    hospitalImg: '',
    isHospital: true, // 对应 radio 的 1/2
    hospitalCount: '',
    hospitalCountTow: '',
    hospitalAddTow: '', // 注意：模板中用的是这个
    hospitalPhone: '',
    departments: [] as number[], // 👈 关键：ID 数组
    intro: '',
    createName: store.account.UserNickName || '未知用户',
    head: '三甲', // 如果后端需要保留
    command: 'AddHospital'
})

// 提交
const hospadd = () => {
    // 可选：简单校验
    if (!hospdata.name) {
        ElMessage.warning('请输入医院名称')
        return
    }
    const selectedDepts = hospdata.departments.map(id => {
        const item = data.value.find(d => d.key === id)
        return {
            departmentId: id,
            name: item?.label || '未知科室'
        }
    })

    // 构造最终提交数据
    const payload = {
        ...hospdata,
        departments: selectedDepts // 替换为对象数组
    }
    Write.post("/AddHospital", hospdata)
        .then((res) => {
            if (res.data.code === 200) {
                ElMessage.success('添加成功')
                router.push('/HospitalShowView')
            } else {
                ElMessage.error(res.data.message || '添加失败')
            }
        })
        .catch((error) => {
            ElMessage.error('请求失败：' + (error.response?.data?.message || error.message))
            console.error(error)
        })
}

// 科室 transfer 数据
interface Option {
    key: number
    label: string
}

const data = ref<Option[]>([])
const loading = ref(false) // ✅ 正确定义 loading

const loadDepartments = async () => {
    loading.value = true
    try {
        const res = await Read.get("/SelectShow")
        if (Array.isArray(res.data.data)) {
            data.value = res.data.data.map((item: { departmentId: any; name: any }) => ({
                key: item.departmentId,
                label: item.name
            }))
        }
    } catch (error) {
        ElMessage.error('获取科室数据失败')
    } finally {
        loading.value = false
    }
}

// 返回
const set = () => {
    router.push('/HospitalShowView')
}

onMounted(() => {
    loadDepartments()
})

// ===== 富文本编辑器 =====
const editorRef = shallowRef()
const valueHtml = ref('<p>请在此编辑表单内容...</p>')

const toolbarConfig = {}
const editorConfig = {
    placeholder: '请输入内容...'
}

const handleCreated = (editor: any) => {
    editorRef.value = editor
}

const handleEditorChange = (editor: { getHtml: () => string }) => {
    valueHtml.value = editor.getHtml()
}

onBeforeUnmount(() => {
    if (editorRef.value) editorRef.value.destroy()
})

</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
<style scoped>
.form-field {
    display: inline-block;
    background: #e3f2fd;
    border: 1px solid #2196f3;
    border-radius: 4px;
    padding: 0 6px;
    margin: 0 2px;
    color: #1976d2;
    font-size: 14px;
    line-height: 1.8;
    cursor: default;
    user-select: none;
}
</style>